/* 
Scenic Graphics Library
Copyright (C) 2007 Jouni Tulkki

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USApackage scenic;
*/

package scenic.toolkit;

import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;

import scenic.ScenicGraphics;
import scenic.toolkit.db.NodeArray;
import scenic.toolkit.db.SyncVector;
import scenic.toolkit.db.event.ChangeEvent;

public class PanelView extends ComponentView {
	private ChildVector children;
	
	@SuppressWarnings("serial")
	private class ChildVector extends SyncVector<ComponentView> {
		public ChildVector() {
			super(getModel().getChildren());
		}
		
		public ComponentView createObject(int index, Object sourceNode) {
			ComponentView c = ((PanelChild)sourceNode).getComponent().createComponent();
			
			addChild(c);
			updateChildren();
			return c;
		}

		public void removeObject(int index, Object object) {
			removeChild((ComponentView)object);
			updateChildren();
		}		
	}
	
	public PanelView(PanelModel model) {
		super(model);
		children = new ChildVector();
	}
	
	public PanelView() {
		super(new PanelModel());
		children = new ChildVector();
	}
	
	public PanelModel getModel() {
		return (PanelModel)super.getModel();
	}
	
	public ComponentView getChildAt(Point2D p) {
		for(int i = children.size() - 1; i >= 0; i--) {
			if(children.elementAt(i).isInside(p))
				return children.elementAt(i);
		}
		return null;
	}
	
	public void changed(ChangeEvent event) {
		updateChildren();
	}
	
	private void updateChildren() {
		invalidate();
	}
	
	public void paint(ScenicGraphics g) {
		NodeArray<PanelChild> childModels = getModel().getChildren();
		
		for(int i = 0; i < children.size(); i++) {
			PanelChild a = childModels.get(i);
			AffineTransform affine = AffineTransform.getTranslateInstance(a.getX(), a.getY());
			ComponentView c = children.elementAt(i);

			System.out.println("X: " + a.getX() + " Y: " + a.getY() + " Component: " + c);
			
			getScene().add(c.getScene());
			c.getScene().setTransform(affine);
			c.setWidth(a.getWidth());
			c.setHeight(a.getHeight());
		}				
	}
}
